<template>
  <div v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <FormItem name="email" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.email"
          :placeholder="t('sys.login.email')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="carbon-email" />
          </template>
        </Input>
      </FormItem>

      <FormItem name="verifyCode" class="enter-x">
        <CaptchaInput
          size="large"
          v-model:value="formData.verifyCode"
          :placeholder="t('sys.login.verifyCode')"
          :getCaptchaApi="refreshVerifyCode"
          icon="flat-color-icons:edit-image"
          class="fix-auto-fill"
        />
      </FormItem>

      <Button
        type="primary"
        class="enter-x"
        size="large"
        block
        @click="handleSendConfirmEmail"
        :loading="loading"
      >
        {{ t('sys.login.confirmTitle') }}
      </Button>
      <Button size="large" block class="mt-4 enter-x" @click="handleBack">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, toRaw, unref, computed, watchEffect, h } from 'vue';

  import LoginFormTitle from './LoginFormTitle.vue';
  import { Form, Input, Button } from 'ant-design-vue';
  import { CaptchaInput } from '@/components/Captcha';
  import Icon from '@/components/Icon/Icon.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useDesign } from '@/hooks/web/useDesign';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum } from './useLogin';

  import { getVerifyCode } from '@/api/sys';
  import { sendConfirmEmail } from '@/api/identity';

  const FormItem = Form.Item;

  const { t } = useI18n();
  const { prefixCls } = useDesign('login');
  const { createErrorModal } = useMessage();
  const { handleBackLogin, handleAjaxResult, getLoginState, setUserAccount, getUserAccountState } =
    useLoginState();

  const formRef = ref();
  const loading = ref(false);

  const formData = reactive({
    email: '',
    verifyCode: '',
    verifyCodeId: '',
  });

  const { getFormRules } = useFormRules(formData);
  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.SEND_CONFIRM_EMAIL);

  watchEffect(async () => {
    const userAccountState = computed(() => unref(getUserAccountState));
    formData.email = userAccountState.value;
  });

  /** 处理发送邮箱激活邮件 */
  async function handleSendConfirmEmail() {
    loading.value = true;
    try {
      const data = await validForm();
      if (!data) return;
      //console.log(data);
      setUserAccount(formData.email);
      const dto = toRaw({
        Email: formData.email,
        EmailConfirmUrl: `${window.location.origin}/#/confirm-email`,
        VerifyCode: formData.verifyCode,
        VerifyCodeId: formData.verifyCodeId,
      });
      const ajaxResult = await sendConfirmEmail(dto);
      if (ajaxResult.Succeeded) {
        clearFormData();
        handleAjaxResult(ajaxResult, LoginStateEnum.CONFIRM_RESULT);
      } else {
        showErrorModal(t('sys.api.errorTip'), ajaxResult.Content);
      }
    } catch (error: any) {
      showErrorModal(t('sys.api.errorTip'), error?.message || t('sys.api.networkExceptionMsg'));
    } finally {
      loading.value = false;
    }
  }

  /** 处理返回 */
  async function handleBack() {
    clearFormData();
    handleBackLogin();
  }

  /** 刷新验证码 */
  async function refreshVerifyCode() {
    const verifyCodeDto = await getVerifyCode();
    formData.verifyCodeId = verifyCodeDto.Id;
    return verifyCodeDto.Image;
  }

  /** 清除表单数据 */
  function clearFormData() {
    formData.verifyCode = '';
    formData.verifyCodeId = '';
  }

  function showErrorModal(title: string, content: string) {
    createErrorModal({
      title: () => h('span', title),
      content: () => h('span', content),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    });
  }
</script>
